#region Copyright (C) 2007 Jens Winter

//Copyright (C) 2007 Jens Winter

//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.

//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//Lesser General Public License for more details.

//You should have received a copy of the GNU Lesser General Public
//License along with this library; if not, write to the Free Software
//Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using Castle.MicroKernel;
using Castle.Windsor;
using Flynn.Core;
using Flynn.TaskServices;

namespace Flynn
{
    public class ConsoleRunner
    {
        private readonly Engine _engine;
        private readonly IWindsorContainer _container;

        public ConsoleRunner(Engine engine) : this(engine, new WindsorContainer("Flynn.Windsor.xml"))
        {
        }

        public ConsoleRunner(Engine engine, IWindsorContainer container)
        {
            if (engine == null)
                throw new ArgumentNullException("engine");

            _engine = engine;
            _container = container;
        }

        public string Execute(string[] args)
        {
            if (args == null)
                throw new ArgumentNullException("args");

            IEnumerable<string> tasks = from a in args
                                        where a.StartsWith("/task:")
                                        select a.Replace("/task:", "");

            if (tasks.Count() == 0)
                return "Failure: No task specified";

            if (!_container.Kernel.HasComponent(tasks.First()))
                return string.Format("Failure: Can't execute task '{0}'", tasks.First());

            ITaskService taskService = (ITaskService)_container[tasks.First()];

            IEnumerable<string> taskArgs = from a in args
                                           where !a.StartsWith("/task:")
                                           select a;

            return taskService.Execute(_engine, taskArgs.ToArray());
        }
    }
}